package com.datas.service.baseentity;

import com.datas.beans.DatatablesPager;
import com.datas.db.hibernatebeans.UmsUser;
import com.datas.service.GuanlianService;
import com.datas.utils.hbn.HbnTxRuner;
import org.hibernate.Session;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by jige0727 on 2017/5/28.
 * 账号
 */
@Service
public class UsersService {
    @Autowired
    GuanlianService guanlianService;

    public Integer create(UmsUser user) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                user.setPassword(UmsUser.encodePass(user.getPassword()));
                return create(user, getCurrentSession());
            }
        }.runTx();
        return res;
    }

    public Integer create(UmsUser user, Session session) {
        session.save(user);
        return user.getId() != null ? 1 : 0;
    }

    /**
     * 这个编辑不改密码
     *
     * @param user
     * @return
     */
    public Integer modify(UmsUser user) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                return modify(user, getCurrentSession());
            }
        }.runTx();
        return res;
    }

    private Integer modify(UmsUser user, Session session) {
        UmsUser dataInDb = session.get(UmsUser.class, user.getId());
        if (dataInDb.getUsername().equals("admin")) {
            return 0;
        }
        user.setCreate_date(dataInDb.getCreate_date());
        user.setModify_date(new Date());
        user.setUsername(dataInDb.getUsername());
        user.setPassword(dataInDb.getPassword());
        session.evict(dataInDb);

        session.update(user);
        return 1;
    }

    /**
     * 返回 1成功 0失败，有子节点
     *
     * @param id
     * @return
     */
    public Integer delete(Integer id) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                UmsUser data = getCurrentSession().get(UmsUser.class, id);
                guanlianService.delGl_all_user(id, getCurrentSession());
                getCurrentSession().delete(data);
                return 1;
            }
        }.runTx();
        return res;
    }

    public UmsUser info(Integer id) {
        UmsUser data = (UmsUser) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                return getCurrentSession().get(UmsUser.class, id);
            }
        }.run();
        data.setPassword(null);
        return data;
    }
    /////////////////////////////

    /**
     * 修改密码
     *
     * @param id
     * @param newPass
     * @param oldPass
     * @return 0错误 1成功
     */
    public Integer modifyPassword(Integer id, String newPass, String oldPass) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                return modifyPassword(id, newPass, oldPass, getCurrentSession());
            }
        }.runTx();
        return res;
    }

    private Integer modifyPassword(Integer id, String newPass, String oldPass, Session session) {
        UmsUser dataInDb = session.get(UmsUser.class, id);
        if (dataInDb != null && dataInDb.getPassword().equals(UmsUser.encodePass(oldPass))) {
            dataInDb.setPassword(UmsUser.encodePass(newPass));
            return 1;
        }
        session.update(dataInDb);
        return 0;
    }

    /////////////////////////////////////////
    SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");

    public void list(DatatablesPager pager) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                List<UmsUser> data = list(pager, getCurrentSession());
                pager.setData(data);
                pager.setRecordsFiltered(list_filtered(pager, getCurrentSession()));
                pager.setRecordsTotal(list_total(getCurrentSession()));
                return 1;
            }
        }.run();
        JSONArray dataArr = new JSONArray();
        if (res != null) {
            List<UmsUser> data = (List<UmsUser>) pager.getData();
            for (UmsUser item : data) {
                item.setPassword(null);
                dataArr.put(new JSONObject(item)
                        .put("ruzhi_time", item.getRuzhi_time() != null ? sft.format(item.getRuzhi_time()) : "")
                        .put("lizhizhi_time", item.getLizhizhi_time() != null ? sft.format(item.getLizhizhi_time()) : ""));
            }
        }
        pager.setData(dataArr);
    }

    private List<UmsUser> list(DatatablesPager pager, Session session) {
        String searchValue = pager.getSearchValue();
        String hql = "from UmsUser i " +
                "where i.disabled =0 " +
                "and (i.username like :searchValue " +
                "or i.real_name like :searchValue " +
                "or i.nick_name like :searchValue) ";
        List<UmsUser> data = session.createQuery(hql)
                .setParameter("searchValue", searchValue)
                .setFirstResult(pager.getStart())
                .setMaxResults(pager.getLength())
                .list();
        return data;
    }

    private Long list_filtered(DatatablesPager pager, Session session) {
        String searchValue = pager.getSearchValue();
        String hql = "select count(*) from UmsUser i " +
                "where i.disabled =0 " +
                "and (i.username like :searchValue " +
                "or i.real_name like :searchValue " +
                "or i.nick_name like :searchValue) ";
        Long count = (Long) session.createQuery(hql)
                .setParameter("searchValue", searchValue)
                .uniqueResult();
        return count;
    }

    private Long list_total(Session session) {
        String hql = "select count(*) from UmsUser i " +
                "where i.disabled =0 ";
        Long count = (Long) session.createQuery(hql)
                .uniqueResult();
        return count;
    }

    public Integer modifyPwd(Integer userid, String oldPass, String newPass) {
        return (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                UmsUser user = getCurrentSession().get(UmsUser.class, userid);
                if (user.getPassword().equals(UmsUser.encodePass(oldPass))) {
                    user.setPassword(UmsUser.encodePass(newPass));
                    getCurrentSession().update(user);
                    return 1;
                } else {
                    return 0;
                }
            }
        }.runTx();
    }
}
